import 'package:flutter/material.dart';
import 'dart:async';

import 'package:flutter/services.dart';
import 'package:plugin_image/plugin_image.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  final _pluginImagePlugin = PluginImage();
  Uint8List? _cameraImg;
  Uint8List? _albumImg;
  StreamSubscription? _streamSubscription;

  @override
  void initState() {
    super.initState();

    _streamSubscription = PluginImage.addListen((map) {
      final code = map['code'];
      if (code == 1) {
        _cameraImg = map['image'];
        setState(() {});
      }
    });
  }

  @override
  dispose() {
    super.dispose();
    _streamSubscription?.cancel();
  }

  Future<void> _openAlbum() async {
    try {
      Map? map = await _pluginImagePlugin.openPhotoAlbum();
      if (map != null) {
        if (map["code"] == 1) {
          _albumImg = map['image'];
        }
      }
    } on PlatformException {
      _albumImg = null;
    }
    if (!mounted) return;
    setState(() {});
  }

  void _openCamera() {
    _pluginImagePlugin.openCamera();
  }

  Widget _imageWidget(Uint8List? img) {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 20),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(6)),
        color: Colors.blue,
      ),
      clipBehavior: Clip.hardEdge,
      width: MediaQuery.of(context).size.width - 40,
      height: (MediaQuery.of(context).size.width - 40) / 3 * 2,
      child: img == null ? SizedBox() : Image.memory(img, fit: BoxFit.cover),
    );
  }

  Widget _btnText(String title) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10, vertical: 4),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(3)),
        color: Colors.blue,
      ),
      child: Text(title, style: TextStyle(color: Colors.white)),
    );
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Plugin example app')),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            _imageWidget(_cameraImg),
            TextButton(onPressed: () => _openCamera(), child: _btnText('访问相机')),
            _imageWidget(_albumImg),
            TextButton(onPressed: () => _openAlbum(), child: _btnText('访问相册')),
          ],
        ),
      ),
    );
  }
}
